package oims;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OrderUpdateServlet extends HttpServlet {

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	private void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String id = req.getParameter("id");
		String customer = req.getParameter("customer");
		String strDate = req.getParameter("date");

		OrderRecord rec = new OrderRecord();
		rec.setId(Integer.parseInt(id));
		rec.setCustomer(customer);
		rec.setDate(toDate(strDate, "yyyy-MM-dd"));

		rec.update();

		RequestDispatcher dispatcher = req.getRequestDispatcher("OrderListServlet");
		dispatcher.forward(req, resp);
	}

	public static Date toDate(String value, String format) {
	    if ( value == null || value == "" )
	        return null;
	    if ( format == null || format == "" )
	        format = "yyyy/MM/dd";
	    // 日付フォーマットを作成
	    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
	    // 日付の厳密チェックを指定
	    dateFormat.setLenient(false);
	    try {
	        // 日付値を返す
	        return dateFormat.parse(value);
	    } catch ( ParseException e ) {
	        // 日付値なしを返す
	        return null;
	    } finally {
	        dateFormat = null;
	    }
	}
}
